package app

import (
	"database/sql"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"log"
)

func errorHandler(ctx *gin.Context) {
	ctx.Next()
	//在业务函数执行结束后，根据Keys中记录的error进行错误处理
	if tmp, ok := ctx.Get("errors"); ok {
		err := tmp.(error)
		switch {
		case errors.Is(err, sql.ErrNoRows):
			ctx.JSON(200, gin.H{"errors": "no such row in system"})
		default:
			ctx.JSON(500, gin.H{"errors": "internal errors"})
		}
		log.Printf("handle request failed, path is %s, reason is %v, stack is %+v", ctx.Request.RequestURI, err, err)
	} else {
		log.Printf("handle request succeed, path is %s", ctx.Request.RequestURI)
	}
}
